

// 使用poll实现多路转接
#include <iostream>
#include <memory>
#include <sys/poll.h>
#include <unistd.h>
#include <algorithm>
#include "Socket.hpp"

using namespace SocketModule;

class PollServer
{
    const static int defaultfd = -1;
    const static int size = 4096;

public:
    PollServer(int port) : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        for (int i = 0; i < size; i++)
        {
            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }

        // 将listen套接字设置为第一个,并设置关心读事件
        _fds[0].fd = _listensock->Fd();
        _fds[0].events = POLLIN;
    }
    void start()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = poll(_fds, size, timeout);

            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪了...";
                Dispatcher();
                break;
            }
        }
        _isrunning = false;
    }
    // 事件派发器
    void Dispatcher()
    {
        for (int i = 0; i < size; i++)
        {
            // 判断fd是否合法
            if (_fds[i].fd == defaultfd)
                continue;

            // 判断读事件是否就绪
            if (_fds[i].revents & POLLIN)
            {
                if (_fds[i].fd == _listensock->Fd())
                {
                    // 如果是监听套接字，则获取底层的连接
                    Accepter();
                }
                else
                {
                    // 如果是普通套接字，则读取数据
                    Recver(i);
                }
            }
        }
    }
    // 链接获取
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        if (sockfd < 0)
        {
            std::cerr << "accept error" << std::endl;
            return;
        }
        // 管理新连接，添加到pollfd数组中
        int pos = 0;
        for (; pos < size; pos++)
        {
            if (_fds[pos].fd == defaultfd)
                break;
        }

        if (pos == size)
        {
            // 说明poll数组已经满了，可以选择扩容，也可以选择丢弃掉该连接
            // 这里选择直接丢弃
            LOG(LogLevel::INFO) << "poll server is full";
            close(sockfd);
        }
        else
        {
            _fds[pos].fd = sockfd;
            _fds[pos].events = POLLIN;
            _fds[pos].revents = 0;
        }
    }
    // IO处理
    void Recver(int i)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[i].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit...";
            close(_fds[i].fd);

            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        else
        {
            LOG(LogLevel::INFO) << "recv error";
            close(_fds[i].fd);

            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
    }
    void stop()
    {
        _isrunning = false;
    }
    ~PollServer()
    {
    }

private:
    bool _isrunning;
    std::unique_ptr<Socket> _listensock;
    struct pollfd _fds[size];
};
